#!/usr/bin/env bash
set -e
export -n CDPATH

VERSION="0.0.1"
export APP_COMMANDS="upload"

if [ -n "$APP_DEBUG" ]; then
  export PS4='+ [${BASH_SOURCE##*/}:${LINENO}] '
  set -x
fi

absolutename() { readlink -f "$1"; }
bin_path=`dirname $(absolutename "$0")`
APP_ROOT=`dirname "$bin_path"`
export APP_ROOT

shopt -s nullglob

for plugin_bin in "${APP_ROOT}/plugins/"*/bin; do
  bin_path="${bin_path}:${plugin_bin}"
done
export PATH="${bin_path}:${PATH}"

hook_path="${APP_HOOK_PATH}:${APP_ROOT}/app.d:/usr/local/etc/app.d:/etc/app.d:/usr/lib/app/hooks"
for plugin_hook in "${APP_ROOT}/plugins/"*/etc/app.d; do
  hook_path="${hook_path}:${plugin_hook}"
done
export APP_HOOK_PATH="$hook_path"

shopt -u nullglob

command="$1"
case "$command" in
"" | "-h" | "--help" )
  echo -e "app $VERSION\n$(app-help)" >&2
  ;;
"-v" )
  exec app---version
  ;;
* )
  command_path="$(command -v "app-$command" || true)"
  if [ -z "$command_path" ]; then
    echo "app: no such command \`$command'" >&2
    exit 1
  fi

  shift 1
  exec "$command_path" "$@"
  ;;
esac
